package cn.edu.nju.software.action.order;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.bean.show.BookItemInOrder;
import cn.edu.nju.software.bean.show.OrderSearchListItem;
import cn.edu.nju.software.bean.show.OrderShow;
import cn.edu.nju.software.bean.show.UserShow;
import cn.edu.nju.software.bean.storage.Order;
import cn.edu.nju.software.service.intf.OrderService;
import cn.edu.nju.software.util.Constants;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class GetOrdersAction extends ActionSupport implements SessionAware {
	
	private int id;
	private String user;
	private int status = -1;
	private Date beginDate;
	private Date endDate;
	private String title;
	private OrderService orderService;
	private Map<String, Object> session;

	public void setId(int id) {
		this.id = id;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public void setBeginDate(Date beginDate) {
		this.beginDate = beginDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	@Override
	public String execute() throws Exception {
		if (id<=0 && user==null && status<0 && beginDate==null && endDate==null && title==null) {
			return INPUT;
		}
		List<OrderSearchListItem> ordersItems = orderService.searchOrders(id, user, status, beginDate, endDate, title);
		int size = ordersItems.size();
		Map<Integer, OrderShow> ordersMap = new LinkedHashMap<Integer, OrderShow>(size);
		Map<Integer, String[]> ordersAddressMap = new LinkedHashMap<Integer, String[]>(size);
		Map<Integer, List<BookItemInOrder>> ordersBooksMap = new LinkedHashMap<Integer, List<BookItemInOrder>>(size);
		for (OrderSearchListItem orderItem : ordersItems) {
			UserShow user = new UserShow(orderItem.getUserName());
			Order order = orderItem.getOrder();
			int orderID = order.getOrderID();
			ordersMap.put(orderID, new OrderShow(order, user));
			ordersAddressMap.put(orderID, order.getAddress().split(Constants.ADDRESS_SEPARATOR));
			ordersBooksMap.put(orderID, orderService.getOrderBooks(order.getOrderID()));
		}
		ordersItems = null;
		session.put(Constants.SESSION_ORDERS, ordersMap);
		session.put(Constants.SESSION_ORDERS_ADDRESS, ordersAddressMap);
		session.put(Constants.SESSION_ORDERS_BOOKS, ordersBooksMap);
		return SUCCESS;
	}

}
